package com.pinganfu.mock.control;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mysql.jdbc.Connection;
import com.pinganfu.mock.model.AsynchronousMouldEntity;
import com.pinganfu.mock.model.AsynchronousResultEntity;
import com.pinganfu.mock.service.IAsynchronousMouldService;
import com.pinganfu.mock.service.IAsynchronousResultService;
import com.pinganfu.mock.service.ITrendsService;

@Controller
@RequestMapping(value = "/ASynchronous", produces = { "application/json;charset=UTF-8"})
public class ASynchronousControl {
	@Resource
	private IAsynchronousMouldService iAsynchronousMouldService;
	
	@Resource
	private IAsynchronousResultService iAsynchronousResultService;
	
	@Resource
	private ITrendsService iTrendsService;
	
	/***************************************http******************************************/
	
	/**
	 * 按条件查询数据
	 * @param id
	 * @param serviceName
	 * @return
	 */
	@RequestMapping(value="/getAsynchronousHttpMouldList",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String getAsynchronousHttpMouldList(@RequestParam(required = false) Integer  id,@RequestParam(required = false) String  serviceName){

		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null != id)
			resultMap.put("id", id);
		if (null != serviceName)
		   	resultMap.put("serviceName", serviceName);
		
		List<AsynchronousMouldEntity> entities = iAsynchronousMouldService.getAsynchronousHttpMouldList(resultMap);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("asynMouldList", entities);
   		return json.messageToJsonString();
	}
	
	
	@RequestMapping(value="/insertAsynchronousHttpMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String insertAsynchronousHttpMould(
			@RequestParam String serviceName,
			@RequestParam String responseUrl,
			@RequestParam String responseMould,
			@RequestParam String receiptUrl,
			@RequestParam String receiptMould
			){
		AsynchronousMouldEntity entity = new AsynchronousMouldEntity();
		entity.setServiceName(serviceName);
		entity.setReceiptUrl(receiptUrl);
		entity.setReceiptMould(receiptMould);
		entity.setResponseUrl(responseUrl);
		entity.setResponseMould(responseMould);
		entity.setCreateTime(new Date());
		
		Integer id = iAsynchronousMouldService.insertAsynchronousHttpMould(entity);
		
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("insertAsynMould", id);
   		return json.messageToJsonString();
	}
	
	
	@RequestMapping(value="/updateAsynchronousHttpMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String updateAsynchronousHttpMould(
			@RequestParam Integer id,
			@RequestParam String serviceName,
			@RequestParam String responseUrl,
			@RequestParam String responseMould,
			@RequestParam String receiptUrl,
			@RequestParam String receiptMould
			){
		AsynchronousMouldEntity entity = new AsynchronousMouldEntity();
		entity.setId(id);
		entity.setServiceName(serviceName);
		entity.setReceiptUrl(receiptUrl);
		entity.setReceiptMould(receiptMould);
		entity.setResponseUrl(responseUrl);
		entity.setResponseMould(responseMould);
		
		iAsynchronousMouldService.updateAsynchronousHttpMould(entity);
		
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("updateAsynMould", entity.getId());
   		return json.messageToJsonString();
	}
	
	@RequestMapping(value="/delAsynchronousHttpMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String delAsynchronousHttpMould(
			@RequestParam Integer id
			){
		AsynchronousMouldEntity entity = new AsynchronousMouldEntity();
		entity.setId(id);
		
		iAsynchronousMouldService.delAsynchronousHttpMould(entity);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("delAsynMould", entity.getId());
   		return json.messageToJsonString();
	}
	
	
	
	
	
	/***************************************https******************************************/
	
	
	/**
	 * 按条件查询数据
	 * @param id
	 * @param serviceName
	 * @return
	 */
	@RequestMapping(value="/getAsynchronousHttpsMouldList",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String getAsynchronousHttpsMouldList(@RequestParam(required = false) Integer  id,@RequestParam(required = false) String  serviceName){

		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null != id)
			resultMap.put("id", id);
		if (null != serviceName)
		   	resultMap.put("serviceName", serviceName);
		
		List<AsynchronousMouldEntity> entities = iAsynchronousMouldService.getAsynchronousHttpsMouldList(resultMap);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("asynMouldList", entities);
   		return json.messageToJsonString();
	}
	
	
	@RequestMapping(value="/insertAsynchronousHttpsMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String insertAsynchronousHttpsMould(
			@RequestParam String serviceName,
			@RequestParam String responseUrl,
			@RequestParam String responseMould,
			@RequestParam String receiptUrl,
			@RequestParam String receiptMould
			){
		AsynchronousMouldEntity entity = new AsynchronousMouldEntity();
		entity.setServiceName(serviceName);
		entity.setReceiptUrl(receiptUrl);
		entity.setReceiptMould(receiptMould);
		entity.setResponseUrl(responseUrl);
		entity.setResponseMould(responseMould);
		entity.setCreateTime(new Date());
		
		Integer id = iAsynchronousMouldService.insertAsynchronousHttpsMould(entity);
		
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("insertAsynMould", id);
   		return json.messageToJsonString();
	}
	
	
	@RequestMapping(value="/updateAsynchronousHttpsMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String updateAsynchronousHttpsMould(
			@RequestParam Integer id,
			@RequestParam String serviceName,
			@RequestParam String responseUrl,
			@RequestParam String responseMould,
			@RequestParam String receiptUrl,
			@RequestParam String receiptMould
			){
		AsynchronousMouldEntity entity = new AsynchronousMouldEntity();
		entity.setId(id);
		entity.setServiceName(serviceName);
		entity.setReceiptUrl(receiptUrl);
		entity.setReceiptMould(receiptMould);
		entity.setResponseUrl(responseUrl);
		entity.setResponseMould(responseMould);
		
		iAsynchronousMouldService.updateAsynchronousHttpsMould(entity);
		
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("updateAsynMould", entity.getId());
   		return json.messageToJsonString();
	}
	
	@RequestMapping(value="/delAsynchronousHttpsMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String delAsynchronousHttpsMould(
			@RequestParam Integer id
			){
		AsynchronousMouldEntity entity = new AsynchronousMouldEntity();
		entity.setId(id);
		
		iAsynchronousMouldService.delAsynchronousHttpsMould(entity);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("delAsynMould", entity.getId());
   		return json.messageToJsonString();
	}
	
	
	/*@RequestMapping(value="/getASynchronousResultByUrl",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String getASynchronousResultByUrl(
			@RequestParam(required = false) String responseUrl,
			@RequestParam(required = false) String receiptUrl
			){
		
		String resultString = "参数错误";
		String entity3="";
		Map<String, Object> resultMap1 = new HashMap<String, Object>();
		if (null != responseUrl){
			resultMap1.put("responseUrl", responseUrl);
			String entity2 = iAsynchronousResultService.getASynchronousResultByUrl1(resultMap1);
			resultString=entity2;
		}
			
		Map<String, Object> resultMap2 = new HashMap<String, Object>();
		if (null != receiptUrl){
			resultMap2.put("receiptUrl", receiptUrl);
			entity3 = iAsynchronousResultService.getASynchronousResultByUrl2(resultMap1);
		}
		   	
		System.out.println(entity3.toString());
		
		HttpClientObject HttpClientObject = new HttpClientObject();
		if(null != receiptUrl){
			try {
				Thread.sleep(1000);
				HttpClientObject.http(receiptUrl, entity3);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
   		return resultString;
	}
	
	@RequestMapping(value="/insertASynchronousResult",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String insertASynchronousResult(
			@RequestParam String serviceName,
			@RequestParam String responseUrl,
			@RequestParam String responseMouldContent,
			@RequestParam String receiptUrl,
			@RequestParam String receiptMouldContent
			){
		AsynchronousResultEntity entity = new AsynchronousResultEntity();
		entity.setServiceName(serviceName);
		entity.setReceiptUrl(receiptUrl);
		entity.setReceiptMouldContent(receiptMouldContent);
		entity.setResponseUrl(responseUrl);
		entity.setResponseMouldContent(responseMouldContent);
		entity.setCreateTime(new Date());
		
		Integer id = iAsynchronousResultService.insertASynchronousResult(entity);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("insertAsynMould", id);
   		return json.messageToJsonString();
	}
	*/
	
	
	
	@RequestMapping(value="/gettest",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String gettest(){
		
		String contentInfo = "{\"businessParameters\":{\"attach\":\"\",\"fee_type\":\"\",\"fund_trade_no\":\"009201510230000000297\",\"partner\":\"270\",\"retcode\":\"0000\",\"retmsg\":\"\",\"sign_key_index\":\"1\",\"sp_user\":\"00999000008334820\",\"time_end\":\"20151023140906\",\"total_fee\":\"9853.05\",\"total_fund_units\":\"9903.05\",\"transaction_id\":\"00500010201510230033330000463593\"},\"protocolParameters\":{\"channel_id\":\"PAF\",\"input_charset\":\"GBK\",\"service_version\":\"1.0\",\"sign\":\"47FF4944F159F95DB9F47FF5B4412F89B658A1C9\",\"sign_type\":\"SHA-1\"}}";
		String url="http://10.59.32.13:32800/caps/dhFundResponese.do";
		String resData="";
		HttpClient httpclient = new DefaultHttpClient();
	  	HttpPost post = new HttpPost(url);
	  	StringEntity entity = new StringEntity(contentInfo,"utf-8");//解决中文乱码问题   
	  	entity.setContentEncoding("UTF-8");    
	    entity.setContentType("application/json");    
	    post.setEntity(entity);
	    
	    HttpResponse result;
		try {
			result = httpclient.execute(post);
			resData = EntityUtils.toString(result.getEntity());
			System.out.println(resData);
			post.releaseConnection();
		
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resData;
		
	}
	
	
	
	
	
	
	
	
	
	
	@RequestMapping(value="/http/{responseUrl}",method={ RequestMethod.GET, RequestMethod.POST },produces = "application/json; charset=utf-8")
	public @ResponseBody String test2(@PathVariable String responseUrl){
		
		System.out.println(responseUrl);
		responseUrl = "http://10.59.33.49:8080/MockPlatform/ASynchronous/http/"+responseUrl;
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null != responseUrl)
			resultMap.put("responseUrl", responseUrl);
		
		//拿到第一个模板
		String data = iAsynchronousMouldService.getASynchronousHttpMouldByUrl1(resultMap);
		
		//获取第二个URL
		String receiptUrl = iAsynchronousMouldService.geReceiptUrlHttp(resultMap);
		
		Map<String, Object> resultMap2 = new HashMap<String, Object>();
		if (null != receiptUrl)
			resultMap2.put("receiptUrl", receiptUrl);
		
		//拿到第二个模板
		String data2 = iAsynchronousMouldService.getASynchronousHttpMouldByUrl2(resultMap2);
		
		
		//拿到动态字段集合
		List<String> filed = iTrendsService.getTrendsList();
		final int size =  filed.size();
		String[] arr = (String[])filed.toArray(new String[size]);
		
		//对json数据进行解析
		Map map=new HashMap();  
        JsonConfig jc=new JsonConfig();  
        jc.setClassMap(map);  
        jc.setRootClass(Map.class);  
        jc.setArrayMode(JsonConfig.MODE_LIST);  
        JSONObject jobj=JSONObject.fromObject(data,jc); 
        JSONObject jobj2=JSONObject.fromObject(data2,jc);
		//trendsData trend = new trendsData();
	        //递归遍历  
	    //String heheString =trend.data(arr,data);
	    String json =decodeJSONObject(arr,jobj);
	    String json2 =decodeJSONObject(arr,jobj2);
	    
	    HttpClientObject HttpClientObject = new HttpClientObject();
		if(null != receiptUrl){
			try {
				Thread.sleep(1000);
				HttpClientObject.http(receiptUrl, json2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	    
	    
	    return json;
	}
	
	
	
	@RequestMapping(value="/https/{responseUrl}",method={ RequestMethod.GET, RequestMethod.POST },produces = "application/json; charset=utf-8")
	public @ResponseBody String test3(@PathVariable String responseUrl){
		
		System.out.println(responseUrl);
		responseUrl = "http://10.59.33.49:8080/MockPlatform/ASynchronous/https/"+responseUrl;
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null != responseUrl)
			resultMap.put("responseUrl", responseUrl);
		
		//拿到模板
		String data = iAsynchronousMouldService.getASynchronousHttpsMouldByUrl1(resultMap);
		
		String receiptUrl = iAsynchronousMouldService.geReceiptUrlHttps(resultMap);
		
		Map<String, Object> resultMap2 = new HashMap<String, Object>();
		if (null != responseUrl)
			resultMap2.put("receiptUrl", receiptUrl);
		
		String data2 = iAsynchronousMouldService.getASynchronousHttpsMouldByUrl2(resultMap2);
		
		
		//拿到动态字段集合
		List<String> filed = iTrendsService.getTrendsList();
		final int size =  filed.size();
		String[] arr = (String[])filed.toArray(new String[size]);
		
		//对json数据进行解析
		Map map=new HashMap();  
        JsonConfig jc=new JsonConfig();  
        jc.setClassMap(map);  
        jc.setRootClass(Map.class);  
        jc.setArrayMode(JsonConfig.MODE_LIST);  
        JSONObject jobj=JSONObject.fromObject(data,jc); 
        JSONObject jobj2=JSONObject.fromObject(data2,jc);
		//trendsData trend = new trendsData();
	        //递归遍历  
	    //String heheString =trend.data(arr,data);
	    String json =decodeJSONObject(arr,jobj);
	    String json2 =decodeJSONObject(arr,jobj2);
	    
	    HttpClientObject HttpClientObject = new HttpClientObject();
		if(null != receiptUrl){
			try {
				Thread.sleep(1000);
				HttpClientObject.http(receiptUrl, json2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	    
	    
	    return json;
	}
	
	
	//对json数据进行解析修改
	public String decodeJSONObject(String[] arr,JSONObject json){ 
		Iterator<String> keys=json.keys(); 
		JSONObject jo=null;
		JSONArray ja = null;
		Object o; 
		String key; 
		while(keys.hasNext()){ 
			key=keys.next(); 
			o=json.get(key); 
			if(o instanceof JSONObject){ 
				jo=(JSONObject)o; 
				if(jo.keySet().size()>0){ 
					decodeJSONObject(arr,jo);
				}else{ 
					System.out.println("key "+key); 
				} 
			}else if(o instanceof JSONArray){
				ja = (JSONArray)o;
				for(int i=0;i<ja.size();i++){
					decodeJSONObject(arr,ja.getJSONObject(i));
				}
			}else{
				for (int i = 0; i < arr.length; i++) {
					String cString = arr[i];
					if(cString.equals(key))
					{
						trendsData trend = new trendsData();
						String data = iTrendsService.getTrendsValue(cString);
						String tString = trend.trendString(data);
						System.out.println(tString);
						json.put(key, tString);
					}
				}
				//System.out.println("value"+"--"+key+"--"+o);
			}
		} 
		String hehe = String.valueOf(json);
		return hehe;
	}
	
}
